<?php
/**
 * @author: zhypy<214681832@qq.com>
 * @day: 2020/7/10
 */
declare (strict_types=1);

namespace app\services\pay;

use app\services\activity\StorePinkServices;
use app\services\notice\UserNoticeServices;
use app\services\order\StoreOrderCreateServices;
use app\services\order\StoreOrderStatusServices;
use app\services\product\product\StoreProductServices;
use app\services\user\UserBillServices;
use app\services\user\UserServices;
use crmeb\services\MiniProgramService;
use crmeb\services\WechatService;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 支付统一入口
 * Class PayServices
 * @package app\services\pay
 */
class PayServices
{
    /**
     * 发起支付
     * @param string $payType
     * @param string $openid
     * @param string $orderId
     * @param string $price
     * @param string $successAction
     * @param string $body
     * @return array|string
     */
    public function pay(string $payType, string $openid, string $orderId, string $price, string $successAction, string $body)
    {
        switch ($payType) {
            case 'routine':
                return MiniProgramService::jsPay($openid, $orderId, $price, $successAction, $body);
                break;
            case 'weixinh5':
                return WechatService::paymentPrepare(null, $orderId, $price, $successAction, $body, '', 'MWEB');
                break;
            case 'weixin':
                try {
                    return WechatService::jsPay($openid, $orderId, $price, $successAction, $body);
                } catch (\Exception $e) {
                    return ['error' => true, 'msg' => '请求微信支付失败!'];
                }

                break;
            default:
                throw new ValidateException('支付方式不存在');
                break;
        }
    }

    /**
     * @param $orderInfo
     * @param $userInfo
     * @return bool
     */
    public function pointPay($orderInfo, $userInfo): bool
    {
        /** @var UserServices $userService */
        //$userService = app()->make(UserServices::class);
        /** @var UserBillServices $userBillServices */
        $userBillServices = app()->make(UserBillServices::class);
        /** @var StoreOrderStatusServices $statusService */
        $statusService = app()->make(StoreOrderStatusServices::class);
        /** @var StoreOrderCreateServices $storeOrderCreateServices */
        $storeOrderCreateServices = app()->make(StoreOrderCreateServices::class);
        /** @var StoreProductServices $storeProductServices */
        $storeProductServices = app()->make(StoreProductServices::class);
        $res[] = $storeProductServices->decProductStock(1, intval($orderInfo['combination_id']));
        $orderInfo['pay_time'] = time();
        //$res[] = $userService->addPayCount($userInfo['uid']);
        $res[] = $order = $storeOrderCreateServices->saveOrderData($orderInfo);
        $res[] = $userBillServices->income('pay_product', $userInfo['uid'], $orderInfo['pay_price'], $userInfo['now_money'], $order['id']);
        //新增积分明细
        $integralData = [
            'uid' => $userInfo['uid'],
            'link_id' => $order['id'],
            'type' => 50,
            'pm' => 0,
            'title' => '购买商品消耗积分',
            'number' => $orderInfo['use_integral'],
            'balance' => (int)$userInfo['points'] + $orderInfo['use_integral'],
            'mark' => '购买商品消耗' . $orderInfo['use_integral'] . '积分',
            'add_time' => time()
        ];
        $res[] = Db::table('eb_user_integral_log')->save($integralData);
        $res[] = $statusService->save([
            'oid' => $order['id'],
            'change_type' => 'pay_success',
            'change_message' => '用户付款成功',
            'change_time' => time()
        ]);
        /** @var UserNoticeServices $success */
        $notice = app()->make(UserNoticeServices::class);
        $res[] = $notice->setNotice([
            'uid' => $userInfo['uid'],
            'title' => '付款成功',
            'content' => '您已成功购买积分商品，商品ID:' . $orderInfo['combination_id'],
            'order' => $orderInfo['order_id'],
        ]);

        return in_array(false, $res,true);
    }

    /**
     * @param $orderInfo
     * @param $userInfo
     * @return bool
     */
    public function joinPinkPay($orderInfo, $userInfo): bool
    {
        /** @var UserServices $userService */
        $userService = app()->make(UserServices::class);
        /** @var UserBillServices $userBillServices */
        $userBillServices = app()->make(UserBillServices::class);
        /** @var StoreOrderStatusServices $statusService */
        $statusService = app()->make(StoreOrderStatusServices::class);
        /** @var StorePinkServices $storePinkServices */
        $storePinkServices = app()->make(StorePinkServices::class);
        /** @var StoreOrderCreateServices $storeOrderCreateServices */
        $storeOrderCreateServices = app()->make(StoreOrderCreateServices::class);
        $orderInfo['pay_time'] = time();
        // 发团信息
        $topPink = $storePinkServices->getOne(['id' => intval($orderInfo['pink_id'])]);
        putPinkMsg("团ID:{$topPink['id']}当前参团人数:{$topPink['pink_people']},所需人数:{$topPink['people']}");
        if ($topPink['pink_people'] == $topPink['people']) {
            return false;
        }
        $res[] = $userService->addPayCount($userInfo['uid']);
        $res[] = $order = $storeOrderCreateServices->saveOrderData($orderInfo);
        $res[] = $storePinkServices->incPinkPeople(intval($orderInfo['pink_id']), 'pink_people');
        $res[] = $storePinkServices->joinPink((int)$userInfo['uid'], $topPink);
        $top = $storePinkServices->getOne(['id' => intval($orderInfo['pink_id'])]);
        if ($top['pink_people'] == $top['people']) {
            $top->status = 2;
            $res[] = $top->save();
        }
        $res[] = $userBillServices->income('pay_product', $userInfo['uid'], $orderInfo['pay_price'], $userInfo['now_money'], $order['id']);
        $res[] = $statusService->save([
            'oid' => $order['id'],
            'change_type' => 'pay_success',
            'change_message' => '用户付款成功',
            'change_time' => time()
        ]);
        /** @var UserNoticeServices $success */
        $notice = app()->make(UserNoticeServices::class);
        $res[] = $notice->setNotice([
            'uid' => $userInfo['uid'],
            'title' => '参团成功',
            'content' => '您已成功参团，团ID:' . $orderInfo['pink_id'],
            'order' => $orderInfo['order_id'],
        ]);
        $res[] = $userService->updateFirstInviteInfo($userInfo['uid'], $orderInfo['pay_price']);//推新奖励

        return in_array(false, $res,true);
    }
}
